/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package org.dromara.web.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.executor.RedissonLockExecutor;
import com.lxk.event.ums.UmsUserCreateEvent;
import com.lxk.miniapp.config.WxMaConfiguration;
import com.lxk.ums.domain.vo.UmsUserVo;
import com.lxk.ums.service.IUmsUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.dromara.common.core.domain.model.XcxLoginBody;
import org.dromara.common.core.domain.model.XcxLoginUser;
import org.dromara.common.core.enums.UserStatus;
import org.dromara.common.core.exception.user.UserException;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.system.domain.vo.SysClientVo;
import org.dromara.web.domain.vo.LoginVo;
import org.dromara.web.service.IAuthStrategy;
import org.dromara.web.service.SysLoginService;
import org.springframework.stereotype.Service;

/**
 * 小程序认证策略
 *
 * @author Michelle.Chung
 */
@Slf4j
@Service("xcx" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class XcxAuthStrategy implements IAuthStrategy {

    private final SysLoginService loginService;

    private final LockTemplate lockTemplate;

    private final IUmsUserService umsUserService;


    @Override
    public LoginVo login(String body, SysClientVo client) {
        XcxLoginBody loginBody = JsonUtils.parseObject(body, XcxLoginBody.class);
        ValidatorUtils.validate(loginBody);
        // xcxCode 为 小程序调用 wx.login 授权后获取
//        String xcxCode = loginBody.getXcxCode();
        String tenantId = loginBody.getTenantId();

        // 多个小程序识别使用
        String appid = loginBody.getAppid();
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        try {

            WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getNewPhoneNoInfo(loginBody.getPhoneXcxCode());
            String phoneNumber = phoneNoInfo.getPhoneNumber();
            String openId = "";
            String unionId = "";
            String sessionKey = "";
            if (StrUtil.isNotBlank(loginBody.getXcxCode())) {
                //登录小程序code
                WxMaJscode2SessionResult wxMaJscode2SessionResult = wxService.jsCode2SessionInfo(loginBody.getXcxCode());
                openId = wxMaJscode2SessionResult.getOpenid();
                unionId = wxMaJscode2SessionResult.getUnionid();
                sessionKey = wxMaJscode2SessionResult.getSessionKey();

            }
            // 框架登录不限制从什么表查询 只要最终构建出 LoginUser 即可
            UmsUserVo user = loadUserByXcxPhonenumber(openId, unionId, sessionKey, tenantId, phoneNumber, loginBody);
            XcxLoginUser loginUser = loginService.buildLoginUserByXcx(user, openId, client);
            SaLoginModel model = new SaLoginModel();
            model.setDevice(client.getDeviceType());
            // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
            // 例如: 后台用户30分钟过期 app用户1天过期
            model.setTimeout(client.getTimeout());
            model.setActiveTimeout(client.getActiveTimeout());
            model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
            // 生成token
            LoginHelper.login(loginUser, model);
            LoginVo loginVo = new LoginVo();
            loginVo.setAccessToken(StpUtil.getTokenValue());
            loginVo.setExpireIn(StpUtil.getTokenTimeout());
            loginVo.setClientId(client.getClientId());
            loginVo.setOpenid(openId);
            return loginVo;
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }

    }

    private UmsUserVo loadUserByXcxPhonenumber(String openId, String unionId, String sessionKey, String tenantId, String phonenumber, XcxLoginBody loginBody) {
        return TenantHelper.dynamic(tenantId, () -> {
            LockInfo lock = lockTemplate.lock(StrUtil.format("openId_{}tenantId_{}_phone_{}_usertype_{}", openId, tenantId, phonenumber, loginBody.getUserType()),
                30000L, 5000L, RedissonLockExecutor.class);
            if (ObjectUtil.isNull(lock)) {
                log.warn("用户重复提交：{},{}", tenantId, phonenumber);
                throw new UserException("user.jcaptcha.error", phonenumber);
            }
            try {
                Opt<UmsUserVo> umsUserVoOpt = umsUserService.queryByPhone(phonenumber);
                if (umsUserVoOpt.isEmpty()) {
                    log.info("登录用户：{} 不存在.", phonenumber);
                    // 注册一个新账号
                    UmsUserVo umsUserVo = umsUserService.registerUserByPhone(phonenumber, loginBody.getUserType(),
                        loginBody.getInviterCode(), loginBody.getRegisterDeviceType(), openId, unionId);
                    // 用户创建
                    SpringUtils.publishEvent(new UmsUserCreateEvent().setUserId(umsUserVo.getId()).setUserType(umsUserVo.getUserType()));
                    return umsUserVo;
                } else if (UserStatus.DISABLE.getCode().equals(umsUserVoOpt.get().getStatus())) {
                    log.info("登录用户：{} 已被停用.", phonenumber);
                    throw new UserException("user.blocked", phonenumber);
                }
                UmsUserVo umsUserVo = umsUserVoOpt.get();
                return umsUserVo;
            } finally {
                lockTemplate.releaseLock(lock);
            }


        });
    }

}
